package com.example.a2032.db;

import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.room.Room;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;


import com.example.a2032.db.dao.BindContactDao;
import com.example.a2032.db.dao.BindersDao;
import com.example.a2032.db.dao.ClockDataDao;
import com.example.a2032.db.dao.ContactDataDao;
import com.example.a2032.db.dao.DeviceInfoDao;
import com.example.a2032.db.dao.EcgSaveInfoDao;
import com.example.a2032.db.dao.EmUserDao;
import com.example.a2032.db.dao.GroupsDao;
import com.example.a2032.db.dao.HeartRateDataDao;
import com.example.a2032.db.dao.PPGDataDao;
import com.example.a2032.db.dao.RealTimeStepDao;
import com.example.a2032.db.dao.SleepDataDao;
import com.example.a2032.db.dao.TempDataDao;
import com.hyphenate.util.EMLog;

public class DataDbHelper {
    private static final String TAG = "DemoDbHelper";
    private static DataDbHelper instance;
    private Context mContext;
    private String currentUser;
    private AppDatabase mDatabase;
    static final Migration MIGRATION_1_2 = new Migration(1,2){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL("CREATE TABLE IF NOT EXISTS `deviceInfo` (`deviceAddress` TEXT PRIMARY KEY NOT NULL, `deviceVersion` TEXT )");
        }
    };
    static final Migration MIGRATION_2_3= new Migration(2,3){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
            database.execSQL("CREATE TABLE IF NOT EXISTS `HeartRateData` (`time` TEXT PRIMARY KEY NOT NULL, `heartRate` INTEGER NOT NULL, `dataMode` INTEGER NOT NULL)");
        }
    };
    static final Migration MIGRATION_3_4= new Migration(3,4){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
            database.execSQL("CREATE TABLE IF NOT EXISTS `RealTimeData` (`date` TEXT PRIMARY KEY NOT NULL, `steps` INTEGER NOT NULL, `distance` FLOAT NOT NULL)");
        }
    };
    static final Migration MIGRATION_4_5= new Migration(4,5){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
            database.execSQL("CREATE TABLE IF NOT EXISTS `SleepData` (`date` TEXT PRIMARY KEY NOT NULL, `sleepQuality` TEXT NOT NULL)");
        }
    };
    static final Migration MIGRATION_5_6= new Migration(5,6){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
            database.execSQL("CREATE TABLE IF NOT EXISTS `bindContact` (`phone` TEXT PRIMARY KEY NOT NULL, `kinship` INTEGER NOT NULL,`name` TEXT NOT NULL)");
        }
    };
    static final Migration MIGRATION_6_7= new Migration(6,7){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL("CREATE TABLE IF NOT EXISTS `JstyleClock` (`hour` INTEGER NOT NULL, `minute` INTEGER NOT NULL, `enable` INTEGER NOT NULL, `clockType` INTEGER NOT NULL, `cycle` TEXT NOT NULL,`id` INTEGER NOT NULL, PRIMARY KEY(`id`))");
        }
    };
    static final Migration MIGRATION_7_8= new Migration(7,8){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL("CREATE TABLE IF NOT EXISTS `TempData` (`time` TEXT NOT NULL, `tempValue` REAL NOT NULL, `dataMode` INTEGER NOT NULL, PRIMARY KEY(`time`))");
        }
    };
    static final Migration MIGRATION_8_9= new Migration(8,9){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL("CREATE TABLE IF NOT EXISTS `ContactData` (`id` TEXT NOT NULL, `phone` TEXT, `name` TEXT, `contactId` INTEGER NOT NULL, PRIMARY KEY(`id`))");
        }
    };
    static final Migration MIGRATION_9_10= new Migration(9,10){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL(" CREATE TABLE IF NOT EXISTS `PPGDATA` (`date` TEXT NOT NULL, `dataType` INTEGER NOT NULL, `wearStatus` INTEGER NOT NULL, `heartRate` INTEGER NOT NULL, `moveStatus` INTEGER NOT NULL, `measureValue` INTEGER NOT NULL, `stressValue` INTEGER NOT NULL, `sbpValue` INTEGER NOT NULL, `dbpValue` INTEGER NOT NULL, `measureProgress` INTEGER NOT NULL, PRIMARY KEY(`date`))"
                          );
        }
    };
    static final Migration MIGRATION_10_11= new Migration(10,11){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL(" CREATE TABLE IF NOT EXISTS `EcgSaveInfo` (`date` TEXT NOT NULL, `rootPath` TEXT NOT NULL, PRIMARY KEY(`date`))"
                   );
        }
    };
    static final Migration MIGRATION_11_12= new Migration(11,12){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建的时候一定要加PRIMARY KEY NOT NULL，否则索引会为null
           database.execSQL(" CREATE TABLE IF NOT EXISTS `GroupsBean` (`im` TEXT NOT NULL, `name` TEXT, PRIMARY KEY(`im`))"
                   );
           database.execSQL(" CREATE TABLE IF NOT EXISTS `BindersBean` (`userId` TEXT NOT NULL, `kinship` INTEGER NOT NULL, `im` TEXT, PRIMARY KEY(`userId`))"
                   );
        }
    };
    static final Migration MIGRATION_12_13= new Migration(12,13){

        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

            database.execSQL(" Alter TABLE  `RealTimeData` ADD COLUMN `cal` REAL NOT NULL default 0 ");

        }
    };
    private final MutableLiveData<Boolean> mIsDatabaseCreated = new MutableLiveData<>();

    private DataDbHelper(Context context){
        this.mContext = context.getApplicationContext();
    }

    public static DataDbHelper getInstance(Context context) {
        if(instance == null) {
            synchronized (DataDbHelper.class) {
                if(instance == null) {
                    instance = new DataDbHelper(context);
                }
            }
        }
        return instance;
    }
    public static DataDbHelper getInstance() {
        return instance;
    }
    /**
     * 初始化数据库
     * @param
     */
    public void initDb() {
//        if(currentUser != null) {
//            if(TextUtils.equals(currentUser, user)) {
//                EMLog.i(TAG, "you have opened the db");
//                return;
//            }
//            closeDb();
//        }
//        this.currentUser = user;
      //  String userMd5 = MD5.encrypt2MD5(user);
        // 以下数据库升级设置，为升级数据库将清掉之前的数据，如果要保留数据，慎重采用此种方式
        // 可以采用addMigrations()的方式，进行数据库的升级
        String dbName = String.format("em_%1$s.db", "jstyle");
        EMLog.i(TAG, "db name = "+dbName);
        mDatabase = Room.databaseBuilder(mContext, AppDatabase.class, dbName)
                        .allowMainThreadQueries()
                        .addMigrations(MIGRATION_1_2)
                        .addMigrations(MIGRATION_2_3)
                        .addMigrations(MIGRATION_3_4)
                        .addMigrations(MIGRATION_4_5)
                        .addMigrations(MIGRATION_5_6)
                        .addMigrations(MIGRATION_6_7)
                        .addMigrations(MIGRATION_7_8)
                        .addMigrations(MIGRATION_8_9)
                        .addMigrations(MIGRATION_9_10)
                        .addMigrations(MIGRATION_10_11)
                        .addMigrations(MIGRATION_11_12)
                        .addMigrations(MIGRATION_12_13)
                        .build();
        mIsDatabaseCreated.postValue(true);
    }

    public LiveData<Boolean> getDatabaseCreatedObservable() {
        return mIsDatabaseCreated;
    }

    /**
     * 关闭数据库
     */
    public void closeDb() {
        if(mDatabase != null) {
            mDatabase.close();
            mDatabase = null;
        }
        currentUser = null;
    }

    public EmUserDao getUserDao() {
        if(mDatabase != null) {
            return mDatabase.userDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public GroupsDao getGroupsDao() {
        if(mDatabase != null) {
            return mDatabase.groupsDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public BindersDao getBindersDao() {
        if(mDatabase != null) {
            return mDatabase.bindersDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public HeartRateDataDao getHeartRateDao() {
        if(mDatabase != null) {
            return mDatabase.heartRateDataDao();
        }
        EMLog.i(TAG, "get HeartRateDao failed, should init db first");
        return null;
    }
    public EcgSaveInfoDao getEcgInfoDao() {
        if(mDatabase != null) {
            return mDatabase.ecgSaveInfoDao();
        }
        EMLog.i(TAG, "get EcgSaveInfoDao failed, should init db first");
        return null;
    }
    public BindContactDao getBindContactDao() {
        if(mDatabase != null) {
            return mDatabase.bindContactDao();
        }
        EMLog.i(TAG, "get bindContactDao failed, should init db first");
        return null;
    }
    public ClockDataDao getClockDataDao() {
        if(mDatabase != null) {
            return mDatabase.clockDataDao();
        }
        EMLog.i(TAG, "get bindContactDao failed, should init db first");
        return null;
    }
    public DeviceInfoDao getDeviceInfoDao() {
        if(mDatabase != null) {
            return mDatabase.deviceInfoDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public RealTimeStepDao getRealTimeStepDao() {
        if(mDatabase != null) {
            return mDatabase.realTimeStepDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public ContactDataDao getContactDataDao() {
        if(mDatabase != null) {
            return mDatabase.contactDataDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public SleepDataDao getSleepDataDao() {
        if(mDatabase != null) {
            return mDatabase.sleepDataDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public PPGDataDao getPPGDataDao() {
        if(mDatabase != null) {
            return mDatabase.ppgDataDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
    public TempDataDao getTempDataDao() {
        if(mDatabase != null) {
            return mDatabase.tempDataDao();
        }
        EMLog.i(TAG, "get userDao failed, should init db first");
        return null;
    }
//    public InviteMessageDao getInviteMessageDao() {
//        if(mDatabase != null) {
//            return mDatabase.inviteMessageDao();
//        }
//        EMLog.i(TAG, "get inviteMessageDao failed, should init db first");
//        return null;
//    }
//
//    public MsgTypeManageDao getMsgTypeManageDao() {
//        if(mDatabase != null) {
//            return mDatabase.msgTypeManageDao();
//        }
//        EMLog.i(TAG, "get msgTypeManageDao failed, should init db first");
//        return null;
//    }
//
//    public AppKeyDao getAppKeyDao() {
//        if(mDatabase != null) {
//            return mDatabase.appKeyDao();
//        }
//        EMLog.i(TAG, "get appKeyDao failed, should init db first");
//        return null;
//    }
}
